import { useState, useEffect, useCallback } from "react";

const useCountdown = (targetTime: number) => {
    const calculateTimeLeft = useCallback(() => {
        const now = new Date().getTime();
        const difference = targetTime - now;
        if (difference <= 0) return { days: "00", hours: "00", minutes: "00", seconds: "00" };
        return {
            days: String(Math.floor(difference / (1000 * 60 * 60 * 24))).padStart(2, "0"),
            hours: String(Math.floor((difference / (1000 * 60 * 60)) % 24)).padStart(2, "0"),
            minutes: String(Math.floor((difference / (1000 * 60)) % 60)).padStart(2, "0"),
            seconds: String(Math.floor((difference / 1000) % 60)).padStart(2, "0"),
        };
    }, [targetTime]);

    const [timeLeft, setTimeLeft] = useState(calculateTimeLeft);
    useEffect(() => {
        const timer = setInterval(() => {
            setTimeLeft(calculateTimeLeft()); // 让倒计时每秒更新
        }, 1000);

        return () => clearInterval(timer); // 组件卸载时清除定时器
    }, [calculateTimeLeft]);
    return timeLeft;
}

export default useCountdown;
